package com.yc.web;

import com.yc.services.CartService;
import com.yc.web.DTO.CartDTO;
import com.yc.web.controller.model.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加商品到购物车
     * POST /cart/add
     * @param cartDTO 购物车信息
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseEntity<ResponseResult> addToCart(@RequestBody CartDTO cartDTO) {
        try {
            CartDTO addedCart = cartService.addToCart(cartDTO);
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(ResponseResult.ok("添加购物车成功").setData(addedCart));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("添加购物车失败: " + e.getMessage()));
        }
    }

    /**
     * 根据用户ID查询购物车
     * GET /cart/user/{userId}
     * @param userId 用户ID
     * @return 购物车列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<ResponseResult> getCartByUserId(
            @PathVariable(value = "userId", required = true) Long userId) {
        try {
            List<CartDTO> cartList = cartService.getCartByUserId(userId);
            return ResponseEntity.ok(ResponseResult.ok("查询购物车成功").setData(cartList));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("查询购物车失败: " + e.getMessage()));
        }
    }

    /**
     * 从购物车移除商品
     * DELETE /cart/{cartId}
     * @param cartId 购物车项ID
     * @return 删除结果
     */
    @DeleteMapping("/{cartId}")
    public ResponseEntity<ResponseResult> removeFromCart(
            @PathVariable(value = "cartId", required = true) Long cartId) {
        try {
            boolean success = cartService.removeFromCart(cartId);
            if (success) {
                return ResponseEntity.ok(ResponseResult.ok("移除购物车商品成功"));
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(ResponseResult.error("移除购物车商品失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("移除购物车商品失败: " + e.getMessage()));
        }
    }

    /**
     * 更新购物车商品数量
     * PUT /cart/{cartId}
     * @param cartId 购物车项ID
     * @param requestBody 请求体，可包含quantity(绝对量)或delta(增量)
     * @return 更新结果
     */
    @PutMapping("/{cartId}")
    public ResponseEntity<ResponseResult> updateCartQuantity(
            @PathVariable(value = "cartId", required = true) Long cartId,
            @RequestBody Map<String, Integer> requestBody) {
        try {
            Integer quantity = requestBody.get("quantity");
            Integer delta = requestBody.get("delta");

            // 参数验证
            if (quantity == null && delta == null) {
                return ResponseEntity.badRequest()
                        .body(ResponseResult.error("必须提供quantity或delta参数"));
            }

            CartDTO updatedCart;
            if (delta != null) {
                // 增量模式
                updatedCart = cartService.updateCartByDelta(cartId, delta);
            } else {
                // 绝对量模式
                updatedCart = cartService.updateCartToQuantity(cartId, quantity);
            }

            if(updatedCart == null) {
                return ResponseEntity.ok(ResponseResult.ok("已经移除该商品"));
            }
            return ResponseEntity.ok(ResponseResult.ok("更新购物车数量成功").setData(updatedCart));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("更新购物车数量失败: " + e.getMessage()));
        }
    }
}